// 预约管理页面JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 初始化预约管理功能
    initBookingManagement();
    
    // 初始化筛选功能
    initFilters();
    
    // 初始化时间线
    initTimeline();
    
    // 添加动画效果
    addBookingManagementAnimations();
    
    // 添加交互事件
    addInteractionEvents();
});

// 初始化预约管理功能
function initBookingManagement() {
    // 模拟预约数据
    const bookings = generateMockBookings();
    
    // 渲染预约列表
    renderBookingList(bookings);
    
    // 渲染时间线
    renderTimeline(bookings);
}

// 生成模拟预约数据
function generateMockBookings() {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    
    // 状态数组
    const statuses = ['active', 'completed', 'cancelled', 'pending'];
    
    // 区域数组
    const areas = ['A区', 'B区', 'C区', 'D区'];
    
    // 生成30条模拟数据
    const bookings = [];
    
    for (let i = 0; i < 30; i++) {
        // 随机日期（过去7天到未来7天）
        const randomDays = Math.floor(Math.random() * 14) - 7;
        const bookingDate = new Date(today);
        bookingDate.setDate(today.getDate() + randomDays);
        
        // 随机时间段
        const timeSlots = [
            { start: '08:00', end: '12:00', label: '上午' },
            { start: '14:00', end: '18:00', label: '下午' },
            { start: '18:00', end: '22:00', label: '晚上' },
            { start: '08:00', end: '22:00', label: '全天' }
        ];
        const timeSlot = timeSlots[Math.floor(Math.random() * timeSlots.length)];
        
        // 随机座位号
        const seatNumber = `${areas[Math.floor(Math.random() * areas.length)]}${Math.floor(Math.random() * 50) + 1}`;
        
        // 确定状态
        let status = statuses[Math.floor(Math.random() * statuses.length)];
        const dateDiff = Math.ceil((bookingDate - today) / (1000 * 60 * 60 * 24));
        
        // 根据日期设置合理的状态
        if (dateDiff < 0) {
            // 过去的预约
            status = Math.random() > 0.2 ? 'completed' : 'cancelled';
        } else if (dateDiff === 0 && timeSlot.start <= formatTime(new Date())) {
            // 今天已经开始的预约
            status = 'active';
        } else if (dateDiff === 0) {
            // 今天还未开始的预约
            status = 'pending';
        }
        
        bookings.push({
            id: `BK${10000 + i}`,
            date: bookingDate,
            startTime: timeSlot.start,
            endTime: timeSlot.end,
            timeLabel: timeSlot.label,
            seatNumber,
            status
        });
    }
    
    // 按日期降序排序
    bookings.sort((a, b) => b.date - a.date);
    
    return bookings;
}

// 渲染预约列表
function renderBookingList(bookings) {
    const bookingList = document.querySelector('.booking-list');
    bookingList.innerHTML = '';
    
    if (bookings.length === 0) {
        bookingList.innerHTML = `
            <tr>
                <td colspan="7" class="no-bookings">
                    <div class="no-data-message">
                        <i class="icon-empty"></i>
                        <p>暂无预约记录</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    bookings.forEach(booking => {
        const row = document.createElement('tr');
        row.className = `booking-item booking-${booking.status}`;
        row.setAttribute('data-booking-id', booking.id);
        
        // 获取状态标签
        const statusLabel = getStatusLabel(booking.status);
        
        // 获取操作按钮
        const actionButtons = getActionButtons(booking.status, booking.id);
        
        row.innerHTML = `
            <td class="booking-id">${booking.id}</td>
            <td class="booking-seat">${booking.seatNumber}</td>
            <td class="booking-date">${formatDate(booking.date)}</td>
            <td class="booking-time">${booking.startTime} - ${booking.endTime}</td>
            <td class="booking-status">
                <span class="status-badge ${booking.status}">${statusLabel}</span>
            </td>
            <td class="booking-actions">${actionButtons}</td>
        `;
        
        bookingList.appendChild(row);
    });
    
    // 添加行悬停动画
    const rows = document.querySelectorAll('.booking-item');
    rows.forEach(row => {
        row.style.opacity = '0';
        row.style.transform = 'translateX(-20px)';
        row.style.transition = 'all 0.3s ease';
    });
    
    rows.forEach((row, index) => {
        setTimeout(() => {
            row.style.opacity = '1';
            row.style.transform = 'translateX(0)';
        }, 50 + index * 30);
    });
}

// 渲染时间线
function renderTimeline(bookings) {
    const timelineContainer = document.querySelector('.timeline-container');
    
    // 按日期分组
    const groupedBookings = groupBookingsByDate(bookings);
    
    timelineContainer.innerHTML = '';
    
    // 遍历日期分组
    for (const [date, dateBookings] of Object.entries(groupedBookings)) {
        const dateSection = document.createElement('div');
        dateSection.className = 'timeline-date-section';
        
        // 日期标题
        const dateTitle = document.createElement('h3');
        dateTitle.className = 'timeline-date-title';
        dateTitle.textContent = getDateLabel(new Date(date));
        
        dateSection.appendChild(dateTitle);
        
        // 时间线项目
        const timelineItems = document.createElement('div');
        timelineItems.className = 'timeline-items';
        
        // 按时间升序排序
        dateBookings.sort((a, b) => {
            if (a.startTime === b.startTime) return 0;
            return a.startTime > b.startTime ? 1 : -1;
        });
        
        dateBookings.forEach(booking => {
            const timelineItem = document.createElement('div');
            timelineItem.className = `timeline-item booking-${booking.status}`;
            timelineItem.setAttribute('data-booking-id', booking.id);
            
            // 获取状态标签
            const statusLabel = getStatusLabel(booking.status);
            
            timelineItem.innerHTML = `
                <div class="timeline-marker"></div>
                <div class="timeline-content">
                    <div class="timeline-time">${booking.startTime} - ${booking.endTime}</div>
                    <div class="timeline-details">
                        <span class="timeline-seat">${booking.seatNumber}</span>
                        <span class="status-badge ${booking.status}">${statusLabel}</span>
                    </div>
                </div>
            `;
            
            timelineItems.appendChild(timelineItem);
        });
        
        dateSection.appendChild(timelineItems);
        timelineContainer.appendChild(dateSection);
    }
    
    // 添加时间线动画
    const timelineSections = document.querySelectorAll('.timeline-date-section');
    timelineSections.forEach((section, index) => {
        section.style.opacity = '0';
        section.style.transform = 'translateY(20px)';
        section.style.transition = 'all 0.5s ease';
        
        setTimeout(() => {
            section.style.opacity = '1';
            section.style.transform = 'translateY(0)';
        }, 300 + index * 200);
    });
}

// 按日期分组预约
function groupBookingsByDate(bookings) {
    const grouped = {};
    
    bookings.forEach(booking => {
        const dateKey = booking.date.toISOString().split('T')[0];
        if (!grouped[dateKey]) {
            grouped[dateKey] = [];
        }
        grouped[dateKey].push(booking);
    });
    
    // 按日期排序
    const sortedGrouped = {};
    Object.keys(grouped).sort((a, b) => new Date(b) - new Date(a)).forEach(key => {
        sortedGrouped[key] = grouped[key];
    });
    
    return sortedGrouped;
}

// 获取日期标签
function getDateLabel(date) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    const compareDate = new Date(date);
    compareDate.setHours(0, 0, 0, 0);
    
    if (compareDate.getTime() === today.getTime()) {
        return '今天';
    } else if (compareDate.getTime() === tomorrow.getTime()) {
        return '明天';
    } else {
        const daysDiff = Math.ceil((compareDate - today) / (1000 * 60 * 60 * 24));
        if (daysDiff > 0) {
            return `${daysDiff}天后`;
        } else {
            return `${Math.abs(daysDiff)}天前`;
        }
    }
}

// 获取状态标签
function getStatusLabel(status) {
    const statusMap = {
        'active': '进行中',
        'completed': '已完成',
        'cancelled': '已取消',
        'pending': '待使用'
    };
    
    return statusMap[status] || status;
}

// 获取操作按钮
function getActionButtons(status, bookingId) {
    const buttons = [];
    
    // 根据状态显示不同的按钮
    if (status === 'active' || status === 'pending') {
        buttons.push(`<button class="btn btn-cancel" data-id="${bookingId}">取消</button>`);
    }
    
    if (status === 'completed') {
        buttons.push(`<button class="btn btn-view" data-id="${bookingId}">查看</button>`);
    }
    
    if (status === 'cancelled') {
        buttons.push(`<button class="btn btn-delete" data-id="${bookingId}">删除</button>`);
    }
    
    return buttons.join(' ');
}

// 初始化筛选功能
function initFilters() {
    const statusFilter = document.getElementById('status-filter');
    const timeFilter = document.getElementById('time-filter');
    const searchInput = document.getElementById('search-input');
    
    // 筛选事件
    [statusFilter, timeFilter, searchInput].forEach(element => {
        element.addEventListener('change', applyFilters);
        if (element.tagName === 'INPUT') {
            element.addEventListener('input', debounce(applyFilters, 300));
        }
    });
}

// 应用筛选
function applyFilters() {
    const statusFilter = document.getElementById('status-filter').value;
    const timeFilter = document.getElementById('time-filter').value;
    const searchQuery = document.getElementById('search-input').value.toLowerCase();
    
    // 重新生成并筛选数据
    let bookings = generateMockBookings();
    
    // 状态筛选
    if (statusFilter !== 'all') {
        bookings = bookings.filter(booking => booking.status === statusFilter);
    }
    
    // 时间筛选
    if (timeFilter !== 'all') {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        switch(timeFilter) {
            case 'today':
                bookings = bookings.filter(booking => {
                    const bookingDate = new Date(booking.date);
                    bookingDate.setHours(0, 0, 0, 0);
                    return bookingDate.getTime() === today.getTime();
                });
                break;
            case 'upcoming':
                bookings = bookings.filter(booking => booking.date >= today);
                break;
            case 'past':
                bookings = bookings.filter(booking => {
                    const bookingDate = new Date(booking.date);
                    bookingDate.setHours(0, 0, 0, 0);
                    return bookingDate.getTime() < today.getTime();
                });
                break;
        }
    }
    
    // 搜索筛选
    if (searchQuery) {
        bookings = bookings.filter(booking => 
            booking.id.toLowerCase().includes(searchQuery) ||
            booking.seatNumber.toLowerCase().includes(searchQuery)
        );
    }
    
    // 重新渲染
    renderBookingList(bookings);
    renderTimeline(bookings);
}

// 添加交互事件
function addInteractionEvents() {
    // 事件委托处理预约项操作
    document.querySelector('.booking-list').addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-cancel')) {
            cancelBooking(e.target.getAttribute('data-id'));
        } else if (e.target.classList.contains('btn-delete')) {
            deleteBooking(e.target.getAttribute('data-id'));
        } else if (e.target.classList.contains('btn-view')) {
            viewBooking(e.target.getAttribute('data-id'));
        }
    });
    
    // 导出按钮点击事件
    document.getElementById('export-btn').addEventListener('click', exportBookings);
    
    // 刷新按钮点击事件
    document.getElementById('refresh-btn').addEventListener('click', refreshBookings);
    
    // 时间线项目点击事件
    document.querySelector('.timeline-container').addEventListener('click', function(e) {
        const timelineItem = e.target.closest('.timeline-item');
        if (timelineItem) {
            const bookingId = timelineItem.getAttribute('data-booking-id');
            viewBooking(bookingId);
        }
    });
}

// 取消预约
function cancelBooking(bookingId) {
    if (confirm('确定要取消这个预约吗？')) {
        showToast('预约已取消', 'success');
        // 重新应用筛选以更新列表
        setTimeout(applyFilters, 500);
    }
}

// 删除预约
function deleteBooking(bookingId) {
    if (confirm('确定要删除这个预约记录吗？此操作不可恢复。')) {
        showToast('预约记录已删除', 'success');
        // 重新应用筛选以更新列表
        setTimeout(applyFilters, 500);
    }
}

// 查看预约详情
function viewBooking(bookingId) {
    // 模拟显示预约详情
    showToast(`查看预约 ${bookingId} 的详情`, 'info', 3000);
    
    // 在实际项目中，这里可以打开详情模态框
}

// 导出预约记录
function exportBookings() {
    showToast('正在导出预约记录...', 'info');
    
    setTimeout(() => {
        showToast('导出成功', 'success');
        // 在实际项目中，这里可以实现CSV或Excel导出功能
    }, 1500);
}

// 刷新预约记录
function refreshBookings() {
    // 显示加载动画
    const refreshBtn = document.getElementById('refresh-btn');
    refreshBtn.classList.add('loading');
    
    showToast('正在刷新数据...', 'info');
    
    setTimeout(() => {
        // 重新应用筛选以刷新数据
        applyFilters();
        refreshBtn.classList.remove('loading');
        showToast('数据已刷新', 'success');
    }, 1000);
}

// 添加动画效果
function addBookingManagementAnimations() {
    // 筛选区域动画
    const filterSection = document.querySelector('.filter-section');
    filterSection.style.opacity = '0';
    filterSection.style.transform = 'translateY(-20px)';
    filterSection.style.transition = 'all 0.6s ease';
    
    setTimeout(() => {
        filterSection.style.opacity = '1';
        filterSection.style.transform = 'translateY(0)';
    }, 300);
    
    // 预约列表标题动画
    const listHeader = document.querySelector('.section-header');
    listHeader.style.opacity = '0';
    listHeader.style.transform = 'translateY(20px)';
    listHeader.style.transition = 'all 0.6s ease';
    
    setTimeout(() => {
        listHeader.style.opacity = '1';
        listHeader.style.transform = 'translateY(0)';
    }, 400);
    
    // 时间线标题动画
    const timelineHeader = document.querySelector('.timeline-header');
    timelineHeader.style.opacity = '0';
    timelineHeader.style.transform = 'translateY(20px)';
    timelineHeader.style.transition = 'all 0.6s ease';
    
    setTimeout(() => {
        timelineHeader.style.opacity = '1';
        timelineHeader.style.transform = 'translateY(0)';
    }, 500);
}

// 添加键盘快捷键
function addKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + R 刷新数据
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            refreshBookings();
        }
        
        // Ctrl/Cmd + E 导出数据
        if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
            e.preventDefault();
            exportBookings();
        }
        
        // Ctrl/Cmd + F 聚焦搜索框
        if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
            e.preventDefault();
            document.getElementById('search-input').focus();
        }
    });
}

// 初始化键盘快捷键
addKeyboardShortcuts();

// 自适应响应式调整
function adjustResponsiveLayout() {
    const isMobile = window.innerWidth < 768;
    const bookingTable = document.querySelector('.booking-table');
    const timelineContainer = document.querySelector('.timeline-container');
    
    if (isMobile) {
        bookingTable.classList.add('mobile');
        timelineContainer.classList.add('mobile');
    } else {
        bookingTable.classList.remove('mobile');
        timelineContainer.classList.remove('mobile');
    }
}

// 监听窗口大小变化
window.addEventListener('resize', debounce(adjustResponsiveLayout, 300));

// 初始化响应式布局
setTimeout(adjustResponsiveLayout, 100);